package com.zzx.project.controller;

import com.alibaba.fastjson.JSON;
import com.zzx.project.entity.User;
import com.zzx.project.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.UUID;

//文件上传Controller
@Controller
@RequestMapping("upload")
public class UploadController {
    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

    @Autowired
    UserService userService;

    // 项目根路径下的目录  -- SpringBoot static 目录相当于是根路径下（SpringBoot 默认）

    @RequestMapping(value = "userImg")
    public String upload(@RequestParam(value = "file", required = false) MultipartFile uploadFile, @RequestParam(value = "uid", required = false) String uid, HttpServletRequest request) {
        final String UPLOAD_PATH_PREFIX = "static/userImages/";
        if (uploadFile.isEmpty()) {
            //返回选择文件提示
            request.setAttribute("tip", "选择了空文件");
            System.out.println("选择了空文件");
            return "main/about";
        }
        User user = new User();
        user.setUserid(Integer.parseInt(uid));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        //构建文件上传所要保存的"文件夹路径"--这里是相对路径，保存到项目根路径的文件夹下
        String realPath = new String("src/main/resources/" + UPLOAD_PATH_PREFIX);
        logger.info("-----------上传文件保存的路径【" + realPath + "】-----------");
        //String format = sdf.format(new Date());
        //存放上传文件的文件夹（文件夹后携带上传日期）
        //File file = new File(realPath + format);
        File file = new File(realPath);
        logger.info("-----------存放上传文件的文件夹【" + file + "】-----------");
        logger.info("-----------输出文件夹绝对路径 -- 这里的绝对路径是相当于当前项目的路径而不是“容器”路径【" + file.getAbsolutePath() + "】-----------");
        if (!file.isDirectory()) {
            //递归生成文件夹
            file.mkdirs();
        }
        //获取原始的名字  original:最初的，起始的  方法是得到原来的文件名在客户机的文件系统名称
        String oldName = uploadFile.getOriginalFilename();
        logger.info("-----------文件原始的名字【" + oldName + "】-----------");
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        logger.info("-----------文件要保存后的新名字【" + newName + "】-----------");
        try {
            //构建真实的文件路径
            File newFile = new File(file.getAbsolutePath() + File.separator + newName);
            //转存文件到指定路径，如果文件名重复的话，将会覆盖掉之前的文件,这里是把文件上传到 “绝对路径”
            uploadFile.transferTo(newFile);
            String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/uploadFile/" + newName;
            logger.info("-----------【" + filePath + "】-----------");
            user.setUserimg("/userImages/" + newName);
            int flag = userService.uploadImgById(user);
            if (flag > 0) {
                User user1 = (User) request.getSession().getAttribute("user");
                user1.setUserimg("/userImages/" + newName);
                request.getSession().setAttribute("user", user1);
                System.out.println("Success!");
                return "main/about";
            } else {
                return "main/about";
            }
        } catch (Exception e) {
            System.out.println("Exception!");
            e.printStackTrace();
        }
        return "main/about";
    }

    @RequestMapping(value = "img")
    @ResponseBody
    public Object upload1(@RequestParam(value = "file", required = false) MultipartFile uploadFile, HttpServletRequest request) {
        int cover = 0;
        if (request.getParameter("cover") != null) {
            cover = Integer.parseInt(request.getParameter("cover"));
        }
        final String UPLOAD_PATH_PREFIX = "static/articleImg/";
        if (uploadFile.isEmpty()) {
            //返回选择文件提示
            request.setAttribute("tip", "选择了空文件");
            System.out.println("选择了空文件");
            return "main/about";
        }
        //构建文件上传所要保存的"文件夹路径"--这里是相对路径，保存到项目根路径的文件夹下
        String realPath = new String("src/main/resources/" + UPLOAD_PATH_PREFIX);
        logger.info("-----------上传文件保存的路径【" + realPath + "】-----------");
        //String format = sdf.format(new Date());
        //存放上传文件的文件夹（文件夹后携带上传日期）
        //File file = new File(realPath + format);
        File file = new File(realPath);
        logger.info("-----------存放上传文件的文件夹【" + file + "】-----------");
        logger.info("-----------输出文件夹绝对路径 -- 这里的绝对路径是相当于当前项目的路径而不是“容器”路径【" + file.getAbsolutePath() + "】-----------");
        if (!file.isDirectory()) {
            //递归生成文件夹
            file.mkdirs();
        }
        //获取原始的名字  original:最初的，起始的  方法是得到原来的文件名在客户机的文件系统名称
        String oldName = uploadFile.getOriginalFilename();
        logger.info("-----------文件原始的名字【" + oldName + "】-----------");
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        logger.info("-----------文件要保存后的新名字【" + newName + "】-----------");
        try {
            //构建真实的文件路径
            File newFile = new File(file.getAbsolutePath() + File.separator + newName);
            //转存文件到指定路径，如果文件名重复的话，将会覆盖掉之前的文件,这里是把文件上传到 “绝对路径”
            uploadFile.transferTo(newFile);
            String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/articleImg/" + newName;
            logger.info("-----------【" + filePath + "】-----------");
            request.getSession().setAttribute("uploadURL", "/articleImg/" + newName);
        } catch (Exception e) {
            System.out.println("Exception!");
            e.printStackTrace();
        }
        if (cover == 1) {
            request.getSession().setAttribute("link", "/articleImg/" + newName);
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("link", "/articleImg/" + newName);
        return JSON.toJSONString(map);
    }
}